# -*- coding: utf-8 -*-
"""
Created on Thu Jun  4 16:52:51 2020

@author: Farman
"""

import GeotiffMan
import numpy
import pathlib
import sys



def get_appendix(file_name):
    file_name = pathlib.Path(file_name).name
    return file_name


def get_file_name_in_lat_lon_format(longitude, latitude, appendix='.tif'):
    '''
    Returns N(S)xxE(W)yyy format file name string.
    
    For file name generate of square-degree tiff file.
    '''
    lon = numpy.floor(longitude)
    lat = numpy.floor(latitude)
    lon = 'E%03d'%lon if lon >=0 else 'W%03d'%(-lon)
    lat = 'N%02d'%lat if lat >=0 else 'S%02d'%(-lat)
    return lat + lon + '-' + appendix


def get_file_name_in_lon_lat_format(longitude, latitude, appendix='.tif'):
    '''
    Returns N(S)xxE(W)yyy format file name string.
    
    For file name generate of square-degree tiff file.
    '''
    lon = numpy.floor(longitude)
    lat = numpy.floor(latitude)
    lon = 'E%03d'%lon if lon >=0 else 'W%03d'%(-lon)
    lat = 'N%02d'%lat if lat >=0 else 'S%02d'%(-lat)
    return lon + lat + '-' + appendix


def split_ESACCI_geotiff(tiff_file_to_split, save_path_of_split):
    file_name = pathlib.Path(tiff_file_to_split)
    save_path = pathlib.Path(save_path_of_split)
    geo_tiff = GeotiffMan.GeoTiffMan(file_name)
    geo_transform = geo_tiff.get_geo_transform()
    geo_tran = GeotiffMan.GeoTransform(geo_transform)
    
    for lon in range(-180, 180):
        for lat in range(-90, 90):
            tile_tiff_file = get_file_name_in_lat_lon_format(lon, lat, get_appendix(file_name))
            x_begin, y_begin = geo_tran.get_reverse_project(lon, lat+1)
            x_end,   y_end   = geo_tran.get_reverse_project(lon+1, lat)
            x_size = x_end - x_begin
            y_size = y_end - y_begin
            print(x_begin, y_begin, x_end, y_end, tile_tiff_file)
            geo_tiff.save_as_geotiff(save_path/tile_tiff_file, x_begin, y_begin, x_size, y_size)
    return

if __name__ == '__main__':
    print('Geotiff splitter')
    print('-' * 20)
    
    if len(sys.argv) == 3:
        file_name = sys.argv[1]
        save_path = sys.argv[2]
        split_ESACCI_geotiff(file_name, save_path)
    elif len(sys.argv) == 1:
        file_name = input('Geotiff to split : ')
        save_path = input('Save path of split geotiff : ')
        split_ESACCI_geotiff(file_name, save_path)
    else:
        print('Usage')
        print('=' * 30)
        print('    python ESACCIsplit.py')
        print('    python ESACCIsplit.py [geotiff_to_split] [save_path_of_split]')